"""
URL历史记录管理模块

用于保存和管理用户常用的游戏URL
"""

import json
from pathlib import Path
from typing import List, Dict, Optional
from datetime import datetime


class URLHistory:
    """URL历史记录管理器"""
    
    def __init__(self, history_file: str = "url_history.json"):
        """
        初始化URL历史记录管理器
        
        Args:
            history_file: 历史记录文件名
        """
        self.history_file = Path(__file__).parent.parent.parent / "data" / history_file
        self.history_file.parent.mkdir(parents=True, exist_ok=True)
        self.max_history = 20  # 最多保存20条记录
    
    def load_history(self) -> List[Dict]:
        """
        加载历史记录
        
        Returns:
            List[Dict]: 历史记录列表
        """
        if not self.history_file.exists():
            return []
        
        try:
            with open(self.history_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (json.JSONDecodeError, FileNotFoundError):
            return []
    
    def save_history(self, history: List[Dict]) -> None:
        """
        保存历史记录
        
        Args:
            history: 历史记录列表
        """
        try:
            with open(self.history_file, 'w', encoding='utf-8') as f:
                json.dump(history, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存历史记录失败: {e}")
    
    def add_url(self, url: str, title: str = None) -> None:
        """
        添加URL到历史记录
        
        Args:
            url: 游戏页面URL
            title: 游戏标题（可选）
        """
        history = self.load_history()
        
        # 检查是否已存在
        for item in history:
            if item['url'] == url:
                # 更新访问时间
                item['last_accessed'] = datetime.now().isoformat()
                item['access_count'] = item.get('access_count', 1) + 1
                if title:
                    item['title'] = title
                self.save_history(history)
                return
        
        # 添加新记录
        new_record = {
            'url': url,
            'title': title or self._extract_title_from_url(url),
            'added_time': datetime.now().isoformat(),
            'last_accessed': datetime.now().isoformat(),
            'access_count': 1
        }
        
        history.insert(0, new_record)
        
        # 限制历史记录数量
        if len(history) > self.max_history:
            history = history[:self.max_history]
        
        self.save_history(history)
    
    def get_recent_urls(self, limit: int = 10) -> List[Dict]:
        """
        获取最近使用的URL
        
        Args:
            limit: 返回数量限制
            
        Returns:
            List[Dict]: 最近使用的URL列表
        """
        history = self.load_history()
        
        # 按最后访问时间排序
        history.sort(key=lambda x: x.get('last_accessed', ''), reverse=True)
        
        return history[:limit]
    
    def get_popular_urls(self, limit: int = 10) -> List[Dict]:
        """
        获取最常用的URL
        
        Args:
            limit: 返回数量限制
            
        Returns:
            List[Dict]: 最常用的URL列表
        """
        history = self.load_history()
        
        # 按访问次数排序
        history.sort(key=lambda x: x.get('access_count', 0), reverse=True)
        
        return history[:limit]
    
    def search_urls(self, keyword: str) -> List[Dict]:
        """
        搜索URL历史记录
        
        Args:
            keyword: 搜索关键词
            
        Returns:
            List[Dict]: 匹配的URL列表
        """
        history = self.load_history()
        keyword = keyword.lower()
        
        results = []
        for item in history:
            if (keyword in item['url'].lower() or 
                keyword in item.get('title', '').lower()):
                results.append(item)
        
        return results
    
    def remove_url(self, url: str) -> bool:
        """
        从历史记录中删除URL
        
        Args:
            url: 要删除的URL
            
        Returns:
            bool: 是否成功删除
        """
        history = self.load_history()
        
        for i, item in enumerate(history):
            if item['url'] == url:
                history.pop(i)
                self.save_history(history)
                return True
        
        return False
    
    def clear_history(self) -> None:
        """清空历史记录"""
        self.save_history([])
    
    def _extract_title_from_url(self, url: str) -> str:
        """
        从URL中提取标题
        
        Args:
            url: URL地址
            
        Returns:
            str: 提取的标题
        """
        from urllib.parse import urlparse
        parsed = urlparse(url)
        
        # 尝试从路径中提取游戏ID或名称
        path_parts = parsed.path.strip('/').split('/')
        if path_parts and path_parts[-1]:
            filename = path_parts[-1]
            if '.' in filename:
                name = filename.split('.')[0]
                if name.isdigit():
                    return f"游戏 {name}"
                else:
                    return name.replace('-', ' ').replace('_', ' ').title()
        
        return f"游戏页面 - {parsed.netloc}"
    
    def export_history(self, export_file: str) -> bool:
        """
        导出历史记录到文件
        
        Args:
            export_file: 导出文件路径
            
        Returns:
            bool: 是否成功导出
        """
        try:
            history = self.load_history()
            export_path = Path(export_file)
            
            if export_path.suffix.lower() == '.json':
                with open(export_path, 'w', encoding='utf-8') as f:
                    json.dump(history, f, ensure_ascii=False, indent=2)
            else:
                # 导出为文本格式
                with open(export_path, 'w', encoding='utf-8') as f:
                    f.write("游戏URL历史记录\n")
                    f.write("=" * 50 + "\n\n")
                    
                    for i, item in enumerate(history, 1):
                        f.write(f"{i}. {item.get('title', '未知游戏')}\n")
                        f.write(f"   URL: {item['url']}\n")
                        f.write(f"   添加时间: {item.get('added_time', '未知')}\n")
                        f.write(f"   访问次数: {item.get('access_count', 0)}\n")
                        f.write("\n")
            
            return True
        except Exception as e:
            print(f"导出历史记录失败: {e}")
            return False